package fy.mdm.dao;

import java.io.File;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.json.JSONObject;

import com.soa.eis.adapter.framework.message.IMsgObject;
import com.soa.eis.adapter.framework.message.impl.GroupRecord;
import com.soa.eis.adapter.framework.message.impl.MsgObject;
import com.soa.eis.adapter.framework.requester.IServiceRequester;
import com.soa.eis.adapter.framework.requester.impl.BaseServiceRequester;

import fy.config.FyConfig;
import fy.mdm.bean.SrmMaterialCodeBean;
import fy.util.DBUtil;
import fy.util.MyUtil;
import com.seeyon.ctp.util.UUIDLong;

import com.seeyon.ctp.workflow.event.WorkflowEventData;

public class SrmBCategoryDevelopDao {
	private static Log log = LogFactory.getLog(SrmBCategoryDevelopDao.class);

	private String[] materialCode;
	private String flowcode;

	public JSONObject LookUpInfoBymaterialCode() throws Exception {
		SrmMaterialCodeBean srmMaterialCodeBean = new SrmMaterialCodeBean();
		JSONObject jo = new JSONObject();
		long[] field_id = new long[1];
		long[] reference_fileid = new long[1];
		// 获取服务调用者实例
		for (int i = 0, length = this.materialCode.length; i < length; i++) {
			// for (int i = 0, length =2; i < length; i++) {
			IServiceRequester Requester = BaseServiceRequester.getInstance();
			// List<GroupRecord> grs1 = new ArrayList<GroupRecord>();
			// 定义请求报文对象
			IMsgObject reqMo = new MsgObject(IMsgObject.MOType.initSR);
			String SourceSysID = "06004"; // 请求方(发布方)
			String ServiceID = "02003000000006";// 响应方(发布方)
			// 获取系统时间
			Date date = new Date();
			SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
			String format = simpleDateFormat.format(date);
			// 对请求报文对象进行设置
			reqMo.setSourceSysID(SourceSysID); // 设置报文 请求方系统号
			reqMo.setSerialNO(format.substring(0, 8) + SourceSysID
					+ String.format("%06d", ++MaterialRequestNoTimerTask.requestNo));// 设置报文流水号,第三段表示今天发送的第几的一次报文
			reqMo.setServiceID(ServiceID); // 设置报文 提供方服务号
			reqMo.setServiceDateTime(format); // 设置报文 日期时间
			// reqMo.setReqValue("materrialCode",materialCode[i]);
			// log.info("materialCode:No"+i+" "+materialCode[i]);
			 reqMo.setReqValue("materrialCode",materialCode[i]);
			 
			//reqMo.setReqValue("materrialCode", materialCode[0]);
			// System.out.println("reqMo:"+reqMo);
			log.info("reqMo:" + reqMo);
			IMsgObject respMo = null;
			respMo = Requester.execute(reqMo);
			// System.out.println(respMo);
			log.info("respMo:" + respMo);
			
			List<GroupRecord> record2 = respMo.getResGroupRecord("GetMaterialNameResult");
			for (GroupRecord groupRecord : record2) {
				log.info(groupRecord.getSubGroups("return").get(0).getFieldValue("materialName"));
				// System.out.println("!!!!!!"+groupRecord.getSubGroups("return").get(0).getFieldValue("materialName"));
				srmMaterialCodeBean.setMaterialCode(materialCode[i]);
				
			//	srmMaterialCodeBean.setMaterialCode(materialCode[0]);
				// srmMaterialCodeBean.setMaterialCode("FYGDW1723GTN");
				srmMaterialCodeBean
						.setMaterialName(groupRecord.getSubGroups("return").get(0).getFieldValue("materialName"));

				System.out.println("~~~~~~~~~~~~~~~~999");

			//	field_id[0] = UUIDLong.longUUID();

				// reference_fileid[0]=Long.valueOf("5074464404380337467");

				// updateFileid(String.valueOf(field_id[0]),queryFlowidOption(flowcode));

				// srmMaterialCodeBean.setFileFieldID(String.valueOf(field_id[0]));
				
				
				
				/*
				 * System.out.println("~~~~~~~~~~~~~~~~1"); WorkflowEventData data =new
				 * WorkflowEventData(); System.out.println("~~~~~~~~~~~~~~~~~2"); long
				 * flowid=Long.valueOf(data.getSummaryId());
				 */

				// long flowid=Long.valueOf(queryModuleidOption(queryFlowidOption(flowcode) ));
				// System.out.println("~~~~~~~~~~~~~~~~~AA"+flowid);

				// FileUpload fu=new FileUpload();
				// long[] aa=fu.createFileAttachmentID(flowid,reference_fileid,field_id);
				// System.out.println("~~~~~~~~~~~~~~~~~3"+aa);

			}
		//	String fieldid=updateFile(materialCode[i]);
			//srmMaterialCodeBean.setFileFieldID("111");	
			jo.put(srmMaterialCodeBean.getID(), srmMaterialCodeBean.getJSONObject());
		}
		System.out.println("~~~jo:"+jo);
		log.info("jo:" + jo);
		return jo;
	}

	// 获取flowid
	public String queryFlowidOption(String flowcode) throws Exception {
		System.out.println(flowcode);
		Connection conn = null;
		PreparedStatement pst = null;
		String flowid = null;
		ResultSet rs = null;
		conn = DBUtil.connect(FyConfig.getOA_DB_CONFIG());
		try {
			pst = conn.prepareStatement("SELECT id FROM formmain_15648  WHERE field0018=?");
			pst.setString(1, flowcode);
			rs = pst.executeQuery();
			while (rs.next()) {
				flowid = rs.getString(1);
			}
		} finally {
			DBUtil.close(rs);
			DBUtil.close(pst);
		}
		System.out.println(flowid);
		return flowid;

	}

	// 获取module 绑定使用
	public String queryModuleidOption(String id) throws Exception {
		System.out.println(id);
		Connection conn = null;
		PreparedStatement pst = null;
		String moduleid = null;
		ResultSet rs = null;
		conn = DBUtil.connect(FyConfig.getOA_DB_CONFIG());
		try {
			pst = conn.prepareStatement("SELECT MODULE_id FROM  v3xuser.CTP_CONTENT_ALL  WHERE   content_data_id=?");
			pst.setString(1, id);
			rs = pst.executeQuery();
			while (rs.next()) {
				moduleid = rs.getString(1);
			}
		} finally {
			DBUtil.close(rs);
			DBUtil.close(pst);
		}
		System.out.println(moduleid);
		return moduleid;

	}

	private void updateFileid(String field, String id) throws Exception {
		
		Connection conn = null;
		PreparedStatement pst = null;
		ResultSet rs = null;
		System.out.println(field + "~~~~" + id);
		try {
			conn = DBUtil.connect(FyConfig.getOA_DB_CONFIG());
			conn.setAutoCommit(false);
			pst = conn.prepareStatement("UPDATE formson_15649 SET field0029=? WHERE  formmain_id=?");
			pst.setString(1, field);
			pst.setString(2, id);
			pst.executeUpdate();

		} finally {
			conn.commit();
			DBUtil.close(rs);
			DBUtil.close(pst);
		}
	}

	/*private String updateFile(String code) throws Exception {
		
		String url = getClass().getResource("").getPath();
		System.out.println("url"+url+"code"+code);
		String fileid = null;
		// String
		// url="/u01/Seeyon/A8/ApacheJetspeed/webapps/seeyon/WEB-INF/classes/fy/mdm/dao/";

		GetCategoryInfo gc = new GetCategoryInfo();
		String path = null;
		String savefilepath = null;
		List<Map<String, String>> list = new ArrayList<Map<String, String>>();
		
		list = gc.GetMDMCategoryInfo(code);
		
		System.out.println(list);
		if (list.isEmpty()) {
			fileid = "A";
			log.info("附件为空，请在MDM系统添加！");
		} else {

			FileUpload fu = new FileUpload();
			String token = fu.getToken("OAluo", "oaluo123456");
			System.out.println(token);
			System.out.println("~~~~~~~~~" + list.size());
			StringBuffer buf = new StringBuffer();
			List<String> listFilePath = new ArrayList<String>();
			for (int i = 0; i < list.size(); i++) {
				path = list.get(i).get("ATTACHMENT_PATH");
				savefilepath = list.get(i).get("ATTACHMENT_NAME");

				System.out.println(url + savefilepath);

				fu.downLoadFile(path, url + savefilepath);

				listFilePath.add(url + savefilepath);

				buf.append(url + savefilepath + "|");

			}

			savefilepath = buf.substring(0, buf.length() - 1);
			//List<String> listFileid = new ArrayList<String>();
			// for(int i=0;i<listFilePath.size();i++) {
			System.out.println("savefilepath:"+savefilepath);
			
			fileid = fu.uploadFiles(savefilepath, token);
			
			System.out.println("fileid:"+fileid);
			
			// listFileid.add(fileid);
			// 删除附件
			delFile(savefilepath);
			// }
		}
		return fileid;
	}*/

	public void setCodes(String[] materialCodeArray) {
		this.materialCode = materialCodeArray;
	}

	public void setFlowcode(String flowcode) {
		this.flowcode = flowcode;
	}

	public static void delFile(String savefilepath) {
		File file = new File(savefilepath);
		if (file.exists() && file.isFile())
			file.delete();
	}
}
